package com.yld.car.market;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import cn.yld.car.db.RecentlyViewedDBHelper;

import com.androidquery.AQuery;
import com.lidroid.xutils.BitmapUtils;
import com.yld.car.common.ConstantUtils;
import com.yld.car.common.NetworkProgressUtils;
import com.yld.car.domain.DealerBaseInfo;
import com.yld.car.domain.FilterCarInfo;
import com.yld.car.domain.SearchDetailCar;
import com.yld.car.domain.UserInfo;

public class MySelfAttentionDealerPageActivity extends BaseActivity implements
		OnItemClickListener {

	private ListView list1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		// 去掉标题栏
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.myself_attention_dealer);

		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);

		TextView tv = (TextView) findViewById(R.id.title);
		tv.setText("我关注的经销商");
		mBar = (ProgressBar) findViewById(R.id.progressBar);

		utils = NetworkProgressUtils.getInstance();
		super.onCreate(savedInstanceState);

		list1 = (ListView) findViewById(R.id.list1);
		showButton();

		list1.setOnItemClickListener(this);

	}

	private ProgressBar mBar;

	private void showButton() {

		Button localButton = (Button) findViewById(R.id.leftButton);
		localButton.setVisibility(View.VISIBLE);

		localButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				finish();

			}
		});
	}

	private NetworkProgressUtils utils;

	private class MySelfAttentionDealerTask extends
			AsyncTask<String, String, ArrayList<DealerBaseInfo>> {

		@Override
		protected ArrayList<DealerBaseInfo> doInBackground(String... params) {

			/*
			 * GetDealersBySelf(string dealerId, string nowPage, string
			 * pageSize)
			 * 
			 * 参数一：dealerId:当前登录的用户编号
			 * 
			 * 参数二：nowPage:当前页码，（数参数值例如：“1”）
			 * 
			 * 参数三：pageSize:每页显示条数，（参数值例如：“20”）
			 */

			UserInfo u = (UserInfo) readObject("userInfo");
			HashMap<String, String> allParams = new HashMap<String, String>();

			allParams.put("dealerId", u.getUserId());
			allParams.put("nowPage", "1");
			allParams.put("pageSize", "20");
			Object o = utils.getWebservicesByData(
					ConstantUtils.NAME_SPACE,
					ConstantUtils.ALL_METHROD_NAME.get(35),
					ConstantUtils.NAME_SPACE
							+ ConstantUtils.ALL_METHROD_NAME.get(35),
					ConstantUtils.GET_DEALERS_BY_SELF_URL, allParams);

			System.out.println("dealer:" + o);
			ArrayList<DealerBaseInfo> all = utils.parseDealerAttention(o
					.toString());

			return all;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			mBar.setVisibility(View.VISIBLE);
			list1.setVisibility(View.GONE);
		}

		@Override
		protected void onPostExecute(ArrayList<DealerBaseInfo> result) {

			super.onPostExecute(result);

			mBar.setVisibility(View.GONE);
			list1.setVisibility(View.VISIBLE);
			if (result != null) {

				MyselfAttentionDealerAdapter adapter = new MyselfAttentionDealerAdapter(
						result);
				list1.setAdapter(adapter);
			}
		}

	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View v, int position,
			long id) {

		Object o = adapterView.getAdapter().getItem(position);

		DealerBaseInfo d = (DealerBaseInfo) o;
		Intent intent = new Intent();
		intent.setClass(this, DealerMarketActivity.class);
		intent.putExtra("bId", d.getId());
		startActivity(intent);
		//
		// if (o instanceof SearchDetailCar) {
		//
		// final SearchDetailCar s = (SearchDetailCar) o;
		// new Thread(new Runnable() {
		//
		// /**
		// * { "recordcount":"1", --返回的数据条数 "table": [ { "no":"1", --序列号
		// * "id": "1683", --车辆ID "name": "外白内黑棕", --车辆外饰内饰简称，即这辆车的标题
		// * "classid": "111", --系列ID "press": "115", --价格（单位W） "qhtime":
		// * "2014-04-30", --到港时间（期货才有时间，现货没有时间即为空） "vin": "", --就是车架号
		// * "xppz": "运动包¤扩展真皮内饰¤红卡钳", --选配配置 "companyname": "",
		// * --这辆车所属经销商公司名称 "adddate": "2014-04-11 18:19:33", --这辆车的录入时间
		// * "pinpainame": "玛莎拉蒂", --此车品牌名称 "xiliename": "GHIBLI S Q4",
		// * --此车系列名称 "gangkouname": "张家港", --这辆车所属经销商公司所在港口 "xhorqh":
		// * "期货" --期货还是现货 } …… ] }
		// */
		// @Override
		// public void run() {
		// SQLiteDatabase sqLiteDatabase = mApp.getmDbHelper()
		// .getWritableDatabase();
		// ContentValues values = new ContentValues();
		// values.put(RecentlyViewedDBHelper.ID, s.getId());
		// values.put(RecentlyViewedDBHelper.NO, s.getNo());
		// values.put(RecentlyViewedDBHelper.NAME, s.getName());
		// values.put(RecentlyViewedDBHelper.CLASS_ID, s.getClassid());
		// values.put(RecentlyViewedDBHelper.PRESS, s.getPress());
		// values.put(RecentlyViewedDBHelper.QHTIME, s.getQhtime());
		// values.put(RecentlyViewedDBHelper.ADD_DATE, s.getAdddate());
		// values.put(RecentlyViewedDBHelper.XPPZ, s.getXppz());
		// values.put(RecentlyViewedDBHelper.COMPANY_NAME,
		// s.getCompanyname());
		// values.put(RecentlyViewedDBHelper.PIN_PAI_NAME,
		// s.getPinpainame());
		// values.put(RecentlyViewedDBHelper.XI_LIE_NAME,
		// s.getXiliename());
		// values.put(RecentlyViewedDBHelper.GANG_KOU_NAME,
		// s.getGangkouname());
		// values.put(RecentlyViewedDBHelper.XHORQH, s.getXhorgh());
		// long rowId = sqLiteDatabase.insert(
		// RecentlyViewedDBHelper.RECENT_VIEW_TABLE, null,
		// values);
		// if (rowId > 0) {
		// System.out.println("insert------>插入成功。");
		// } else {
		//
		// System.out.println("insert------>插入失败。");
		// }
		//
		// }
		// }).start();
		//
		// String cId = s.getId();
		// Intent intent = new Intent();
		// intent.putExtra("cId", cId);
		// intent.putExtra("carName", s.getPinpainame());
		// intent.putExtra("carType", s.getXhorgh());// 类型
		// intent.putExtra("carSeries", s.getXiliename());
		//
		// intent.setClass(this, CarDetailInfoActivity.class);
		// startActivity(intent);
		// }

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (1 == requestCode && RESULT_OK == resultCode) {

			FilterCarInfo f = (FilterCarInfo) data
					.getSerializableExtra("filter");

			// System.out.println(s);
			// new CarTypeTask().execute(new String[] { f.color, f.type, f.port
			// });
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		new MySelfAttentionDealerTask().execute("");
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();

	}

	private class MyselfAttentionDealerAdapter extends BaseAdapter {

		public MyselfAttentionDealerAdapter(ArrayList<DealerBaseInfo> infos) {
			this.mDealerBaseInfos = infos;
		}

		private ArrayList<DealerBaseInfo> mDealerBaseInfos;

		@Override
		public int getCount() {

			return mDealerBaseInfos.size();
		}

		@Override
		public Object getItem(int position) {

			return mDealerBaseInfos.get(position);
		}

		@Override
		public long getItemId(int position) {

			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			if (convertView == null) {
				convertView = LayoutInflater.from(
						MySelfAttentionDealerPageActivity.this).inflate(
						R.layout.dealer_attention_item, null);

			}

			ImageView imageView = (ImageView) convertView
					.findViewById(R.id.itemCarImage);
			final DealerBaseInfo d = mDealerBaseInfos.get(position);
			String s = d.getUserimg();
			String downloadUrl = null;
			AQuery aq = new AQuery(MySelfAttentionDealerPageActivity.this);
			if (!s.equals("")) {

				if (s.indexOf("aodi") >= 0) {
					downloadUrl = ConstantUtils.DOWNLOAD_IMAGE_URL_NEW;
				} else {
					downloadUrl = ConstantUtils.DOWNLOAD_IMAGE_URL;
				}
				String imgUploadPath = downloadUrl + d.getUserimg();
				aq.id(imageView).image(imgUploadPath, true, true, 0, 0, null,
						0, 1.0f / 1.0f);
				// BitmapUtils bitmapUtils = new BitmapUtils(
				// getApplicationContext());
				//
				// bitmapUtils.clearCache();
				// bitmapUtils.supportResume();
				// // 加载网络图片
				// bitmapUtils.display(imageView, imgUploadPath);

			} else {

				imageView.setImageResource(R.drawable.splash1);
			}

			TextView itemText1 = (TextView) convertView
					.findViewById(R.id.dealerItem1);
			itemText1.setText(d.getCompname());
			TextView itemText2 = (TextView) convertView
					.findViewById(R.id.dealerItem2);
			itemText2.setText(d.getComppeople());
			TextView itemText3 = (TextView) convertView
					.findViewById(R.id.dealerItem3);
			itemText3.setText(d.getTelephone());
			TextView itemText4 = (TextView) convertView
					.findViewById(R.id.dealerItem4);
			itemText4.setText(d.getAddress());
			Button button = (Button) convertView
					.findViewById(R.id.attentionBtn);
			button.setBackgroundResource(R.drawable.dynamic_bg);
			button.setText("取消关注");

			button.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					new Thread(new Runnable() {

						@Override
						public void run() {
							UserInfo u = (UserInfo) readObject("userInfo");

							String currentDealerId = u.getUserId();
							String toDealerId = d.getId();

							System.out.println("currentDealerId==>"
									+ currentDealerId + ",toDealerId==="
									+ toDealerId);
							HashMap<String, String> allParams = new HashMap<String, String>();

							allParams.put("fromDealersId", currentDealerId);
							allParams.put("toDealersId", toDealerId);

							Object o = utils
									.getWebservicesByData(
											ConstantUtils.NAME_SPACE,
											ConstantUtils.ALL_METHROD_NAME
													.get(37),
											ConstantUtils.NAME_SPACE
													+ ConstantUtils.ALL_METHROD_NAME
															.get(37),
											ConstantUtils.CANCEL_ATTENTION_TO_DEALERS_URL,
											allParams);

							settingAttentionDealerTags(toDealerId);
							Message msg = mHandler.obtainMessage();

							msg.obj = o;
							System.out.println("msg------->" + o);
							mHandler.sendMessage(msg);

						}
					}).start();

				}
			});
			convertView
					.setBackgroundResource(android.R.drawable.list_selector_background);
			return convertView;
		}

	}

	private Handler mHandler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			String m = msg.obj.toString();
			if (m != null && (m.indexOf("操作成功") >= 0)) {
				Toast.makeText(getApplicationContext(), "已取消关注",
						Toast.LENGTH_SHORT).show();

				new MySelfAttentionDealerTask().execute("");

			}

		}
	};
private void settingAttentionDealerTags(String toDealerId){
		
		
		HashMap<String, String> allParams = new HashMap<String, String>();

		allParams.put("userId", toDealerId);

		NetworkProgressUtils utils = NetworkProgressUtils.getInstance();

		Object o = utils.getWebservicesByData(ConstantUtils.NAME_SPACE,
				ConstantUtils.ALL_METHROD_NAME.get(50),
				ConstantUtils.NAME_SPACE
						+ ConstantUtils.ALL_METHROD_NAME.get(50),
				ConstantUtils.SEND_MESSAGE_FOR_ANDROID_TO_BUTTON_URL,
				allParams);
		int index = o.toString().indexOf("获取别名成功，别名为:");
		if (index >= 0) {

			String replace = o.toString().substring(index + 11,
					o.toString().length() - 2);

			String alias[] = replace.split(",");

			Set<String> tags=new HashSet<String>();
			
			for (String string : alias) {
				tags.add(string);
			}
			JPushInterface.setTags(getApplicationContext(), tags, mAliasCallback);
		}
}

private static final String TAG=MySelfAttentionDealerPageActivity.class.getName();
private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

	@Override
	public void gotResult(int code, final String alias, Set<String> tags) {
		String logs;
		switch (code) {
		case 0:
			logs = "Set tag and alias success" + tags;
			Log.i(TAG, logs);
			break;

		case 6002:
			logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
			Log.i(TAG, logs);
			if (NetworkProgressUtils.getInstance().getAPNType(
					getApplicationContext()) != -1) {

				new Thread(new Runnable() {
					public void run() {
						JPushInterface.setAliasAndTags(
								getApplicationContext(), alias, null,
								mAliasCallback);
					}
				}).start();
			} else {
				Log.i(TAG, "No network");
			}
			break;

		default:
			logs = "Failed with errorCode = " + code;
			Log.e(TAG, logs);
		}

		// ExampleUtil.showToast(logs, getApplicationContext());
	}

};

}
